package com.phkj.qdh.ui.fragment.myfailover

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.phkj.qdh.R
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentMyFailoverBinding
import com.phkj.qdh.ui.adapter.usercenter.MyFailoverListAdapter
import com.phkj.qdh.ui.fragment.user.UserVM
import com.phkj.qdh.ui.fragment.user.getUserVMProvider
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest

/**
 * 我的容错申请列表
 */

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

class MyFailoverFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null
    private lateinit var vm: UserVM
    private lateinit var helper: QuickAdapterHelper
    private val pageInfo = PageInfo()
    private val myFailoverListAdapter by lazy { MyFailoverListAdapter() }
    private var _binding: FragmentMyFailoverBinding? = null
    private val binding get() = _binding!!
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentMyFailoverBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getUserVMProvider())[UserVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            srlUseCar.setOnRefreshListener {
                refresh()
            }
            rvUseCar.run {
                layoutManager = LinearLayoutManager(requireContext())
                addItemDecoration(MyItemDecoration(width = 22))
            }
        }

        helper = QuickAdapterHelper.Builder(myFailoverListAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    pageInfo.nextPage()
                    getData()
                }

                override fun onFailRetry() {
                    getData()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlUseCar.isRefreshing
                }
            }).build()

        binding.rvUseCar.adapter = helper.adapter

        myFailoverListAdapter.addOnItemChildClickListener(R.id.tv) { adapter, _, pos ->
            val data = adapter.getItem(pos)
            data?.let {
                parentFragmentManager.commit {
                    addToBackStack("")
                    replace(id, MyFailoverDetailFragment.newInstance(it, ""))
                    setReorderingAllowed(true)
                }
            }

        }

        launchAndRepeatWithViewLifecycle {
            vm.state.collectLatest {
                binding.srlUseCar.isRefreshing = false
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.myFailoverList.collectLatest {
                if (pageInfo.isFirstPage) {
                    myFailoverListAdapter.submitList(it)
                } else {
                    myFailoverListAdapter.addAll(it)
                }
                if (it.size != PAGE_SIZE) {
                    helper.trailingLoadState = LoadState.NotLoading(true)
                } else {
                    helper.trailingLoadState = LoadState.NotLoading(false)
                }

            }
        }
        getData()
    }

    private fun refresh() {
        pageInfo.reset()
        helper.trailingLoadState = LoadState.None
        getData()
    }

    private fun getData() {
        val map = HashMap<String, Any?>()
        map["page"] = pageInfo.page
        map["size"] = PAGE_SIZE
        vm.getMyFailoverList(map)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: String, param2: String) = MyFailoverFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}